package sunwul.hospital.cmn.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import sunwul.hospital.cmn.mapper.DictMapper;
import sunwul.hospital.model.model.cmn.Dict;
import sunwul.hospital.model.vo.cmn.DictEeVo;

/**
 * @author sunwul
 * @date 2023/11/1 14:31:11
 * @description 数据字典监听
 */
public class DictListener extends AnalysisEventListener<DictEeVo> {

    private final Logger log = LoggerFactory.getLogger(DictListener.class);

    private DictMapper dictMapper;

    public DictListener(DictMapper dictMapper) {
        this.dictMapper = dictMapper;
    }

    // 逐行读取
    @Override
    public void invoke(DictEeVo dictEeVo, AnalysisContext analysisContext) {
        // 插入数据库
        Dict dict = new Dict();
        BeanUtils.copyProperties(dictEeVo, dict);
        // 不存在的导入, 字典名称与编码不能重复
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("name",dict.getName());
        wrapper.eq("dict_code",dict.getDictCode());
        int count = dictMapper.selectCount(wrapper);
        if (count == 0) {
            log.info("easyExcel插入数据, origin={}, target={}", dictEeVo, dict);
            dictMapper.insert(dict);
        }
    }

    // 读取完毕执行
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        log.info("easyExcel数据插入完成!");
    }
}
